import java.util.*;

/**
 * Definition for a binary tree node.*/
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

/*迭代实现层次遍历：
这道题的关键是要想到队列，①易错为栈
* */
public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ans =  new ArrayList<>();
        if (root == null) {
            return ans;  // ②这里也要注意涉及node的问题null也会占位
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int len = queue.size();
            List<Integer> list = new ArrayList<>();

            for (int i = 0; i < len; i++) {
                TreeNode trnode = queue.poll();
                list.add(trnode.val);
                if (trnode.left != null) {
                    queue.add(trnode.left);  /* ③这里是易错点，空也会在队列里占位置*/
                }
                if (trnode.right != null) {
                    queue.add(trnode.right);
                }
            }
            ans.add(list);
        }
        return  ans;


    }
}


// 希望你开心点，一起加油！
/*
     _--_  _--_
    -    \/    -
     -        -
       -    -
         -

        _
       \   \
         \    \
         |     |
        /    /
       ... `

*/